﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.API.Infrastructure.Middlewares;
using Casamiel.Application;
using Casamiel.Common;
using Casamiel.Domain;
using Casamiel.Domain.Entity;
using MediatR;
namespace Casamiel.API.Application.Commands
{
	/// <summary>
	/// 
	/// </summary>
	public class CreateMemberAccessTokenComandHandler : IRequestHandler<CreateMemberAccessTokenComand, TokenEntity>
	{
		private readonly IMemberService _memberService;
		private readonly ITokenProvider _tokenProvider;
		private readonly IUserLogService _userLog;
		/// <summary>
		/// 
		/// </summary>
		/// <param name="tokenProvider"></param>
		/// <param name="memberService"></param>
		/// <param name="userLogService"></param>
		public CreateMemberAccessTokenComandHandler(ITokenProvider tokenProvider, IMemberService memberService,IUserLogService userLogService)
		{
			_tokenProvider = tokenProvider;
			_memberService = memberService;
			_userLog = userLogService;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="request"></param>
		/// <param name="cancellationToken"></param>
		/// <returns></returns>
		public async Task<TokenEntity> Handle(CreateMemberAccessTokenComand request, CancellationToken cancellationToken)
		{
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var token = _tokenProvider.GenerateToken(request.Mobile);
			var m = await _memberService.FindAsync<ICasaMielSession>(request.Mobile, request.LogType).ConfigureAwait(false);
			if (m != null)
			{
				m.Access_Token = token.access_token;
				m.UpdateTime = DateTime.Now;
				m.Login_Count++;
				m.Expires_In = token.expires_in;
				m.Resgistration_Id = request.Registration_Id;
				await _memberService.UpdateAsync<ICasaMielSession>(m).ConfigureAwait(false);
			}
			else
			{
				m = new MemberAccessToken
				{
					Access_Token = token.access_token,
					CreateTime = DateTime.Now,
					UpdateTime = DateTime.Now,
					Login_Count = 1,
					Login_Type = request.LogType,
					Mobile = request.Mobile,
					Expires_In = token.expires_in,
					Resgistration_Id = request.Registration_Id
				};
				await _memberService.AddAsync<ICasaMielSession>(m).ConfigureAwait(false);
			}
			var logdata = new UserLog { Url = request.RequestUrl, OPInfo = $"用户登陆", OPTime = DateTime.Now, UserName = request.Mobile, UserIP = request.UserIP };
			await _userLog.AddAsync<ICasaMielSession>(logdata).ConfigureAwait(false);
			return token;
		}
	}
}
